package com.springboot.exp.exp_3.services;

import com.springboot.exp.exp_3.models.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Service
public class CoronaVirusDataService implements InitializingBean {
    /**
     * 数据源url
     */
    private static final String CORONA_VIRUS_DATA_URL = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    private final List<RegionStats> allRegionStats = new ArrayList<>();

    public List<RegionStats> getAllRegionStats(){return allRegionStats;}

    @Scheduled(cron = "${Yip.Schedules.updateVirusDataCron}")

    public void fetchCoronaVirusData() throws IOException {

        //爬取全球新型冠状病毒统计数据的csv文件
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(CORONA_VIRUS_DATA_URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity,Resource.class);
        Resource body = exchange.getBody();

        //通过Resource对象的getInputStream方法获取csv文件的输入流
        InputStream inputStream = body.getInputStream();

        //从字节流转换为字符流
        InputStreamReader inputStreamReader= new InputStreamReader(inputStream);
        Reader in = new BufferedReader(inputStreamReader);

        //处理csv文件中的数据
        Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);

        for (CSVRecord record : records) {
            RegionStats regionStats = new RegionStats();
            regionStats.setState(record .get("Province/State"));
            regionStats.setCountry(record .get("Country/Region"));
            regionStats.setLatestTotalCases(Integer.parseInt(record.get(record.size()-1)));
            regionStats.setDiffFromPrevDay(Integer.parseInt(record.get(record.size()-1))-Integer.parseInt(record.get(record.size()-2)));
            allRegionStats.add(regionStats);
        }

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        fetchCoronaVirusData();
    }
}
